package com.seven.kaisajiami;

public class KaiSaDemo {

    public static void main(String[] args) {
        //定于原文
        String input ="Hello World";
        //把原文右边移动3位
        int key=3;
        //加密后的密文
        String encryptcode = encryptKaiser(input, key);
        //解密后的明文
        String decryptcode=decryptKaiser(encryptcode,key);
        System.out.println("密文=" + encryptcode);
        System.out.println("明文=" + decryptcode);
    }

    /**
     * 凯撒解密
     * @param encryptcode：密文
     * @param key：密钥
     * @return 明文
     */
    public static String decryptKaiser(String encryptcode, int key) {
        char[] chars=encryptcode.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
            int b= aChar;
            //偏移数据
            b=b-key;
            char newb=(char)b;
            sb.append(newb);
        }
        return sb.toString();
    }

    /**
     * 凯撒加密
     * @param input：加密原文
     * @param key：加密位移数（1-25）
     */
    public static String encryptKaiser(String input, int key) {
        //抽取快捷键CTRL+alt+m
        //把字符窜变成字节数组
        char [] chars=input.toCharArray();
        StringBuilder sb=new StringBuilder();
        for (char aChar : chars) {
            int b=aChar;
            //往右边移动3位
            b=b+key;
            char newb=(char) b;
            sb.append(newb);
        }
        return sb.toString();
    }
}
